﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using ThuPhap.Models;
using ThuPhap.Class;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using System.Threading;

namespace ThuPhap.ViewModels
{
    public class StartViewModel
    {
        public ObservableCollection<CreateItem> Items { get; private set; }
        public ObservableCollection<FileViewModel> StoredItems { get; private set; }
        public ObservableCollection<TemplateItem> TemplateItems { get; private set; }
        public ObservableCollection<GalleryItem> GalleryItems { get; private set; }
        public ObservableCollection<TemplateItem> OnlineTemplates { get; private set; }
        public bool IsDataLoaded { get; set; }
        public bool IsConnected { get; set; }
        public StartViewModel()
        {
            this.Items = new ObservableCollection<CreateItem>();
            this.StoredItems = new ObservableCollection<FileViewModel>();
            this.TemplateItems = new ObservableCollection<TemplateItem>();
            this.GalleryItems = new ObservableCollection<GalleryItem>();
            this.OnlineTemplates = new ObservableCollection<TemplateItem>();

            this.IsDataLoaded = false;
            this.IsConnected = true;
            //this.LoadData();
            //this.UpdateGalleryItem();
        }

        public void LoadData()
        {
            //Load Item
            LoadCreateItem();
            //Load saved item
            LoadTemplateItem();

            //Load template
            LoadOnlineTemplateItems();

            //Load Gallery
           

            this.IsDataLoaded = true;
        }
        private delegate void AddItemToCreateItemDelegate(CreateItem CreateItem);
        private void AddItemToCreateItem(CreateItem CreateItem)
        {
            this.Items.Add(CreateItem);
        }

        private delegate void AddItemToStoredItemDelegate(StoredItem StoredItem);
        private void AddItemToStoredItem(StoredItem StoredItem)
        {
            WriteableBitmap writeableBitmap = new WriteableBitmap(480, 800).FromByteArray(StoredItem.Image);
            writeableBitmap = writeableBitmap.Crop(0, (writeableBitmap.PixelHeight - writeableBitmap.PixelWidth) / 2, writeableBitmap.PixelWidth, writeableBitmap.PixelWidth);
            FileViewModel file = new FileViewModel()
            {
                Name = StoredItem.Name + ".tp",
                Date = StoredItem.Date,
                Image = writeableBitmap
            };
            this.StoredItems.Add(file);
        }

        private delegate void AddTemplateToTemplateItemDelegate(Template template);
        private void AddTemplateToTemplateItem(Template template)
        {
            var temp = new TemplateItem();
            temp.Name = template.Name;
            temp.Description = template.Description;
            temp.ID = template.ID;

            var ms = new MemoryStream(template.Image);
            var bmi = new BitmapImage();
            bmi.SetSource(ms);

            temp.Bitmap = new WriteableBitmap(bmi);
            this.TemplateItems.Add(temp);
        }

        private delegate void AddItemToTemplateItemDelegate(TemplateItem TemplateItem);
        private void AddItemToTemplateItem(TemplateItem TemplateItem)
        {
            string url = TemplateItem.Image;
            WriteableBitmap writeableBitmap = new WriteableBitmap(0, 0).FromResource(url);
            var result = writeableBitmap.Crop(0, (writeableBitmap.PixelHeight - writeableBitmap.PixelWidth) / 2, writeableBitmap.PixelWidth, writeableBitmap.PixelWidth);
            TemplateItem.Bitmap = result;
            this.TemplateItems.Add(TemplateItem);
        }

        private delegate void AddOnlineItemToTemplateItemDelegate(TemplateItem TemplateItem);
        private void AddOnlineItemToTemplateItem(TemplateItem TemplateItem)
        {
        }

        public void LoadCreateItem()
        {
            ObservableCollection<CreateItem> createItems = new ObservableCollection<CreateItem>();
            createItems.Add(new CreateItem() { Name = "blank panel", Image = "Resources/Images/new.png", Description = "Create a empty panel" });
            createItems.Add(new CreateItem() { Name = "from template", Image = "Resources/Images/folder.png", Description = "Create panel from existed templates" });
            createItems.Add(new CreateItem() { Name = "online template", Image = "Resources/Images/online.png", Description = "Create panel from online templates" });
            createItems.Add(new CreateItem() { Name = "from camera", Image = "Resources/Images/camera3.png", Description = "Create panel with image from camera" });
            foreach (var item in createItems)
            {
                Deployment.Current.Dispatcher.BeginInvoke(new AddItemToCreateItemDelegate(AddItemToCreateItem), item);
            }
        }

        public void UpdateStoredItem()
        {
            ObservableCollection<StoredItem> storedItems = new ObservableCollection<StoredItem>();
            SavePictureInfo savePicture = new SavePictureInfo();
            storedItems = savePicture.GetData();
            
            foreach (var item in storedItems)
            {
                Deployment.Current.Dispatcher.BeginInvoke(new AddItemToStoredItemDelegate(AddItemToStoredItem), item);
            }
        }

        public void LoadOnlineTemplateItems()
        {
            CalligraphyService.IcalligraphyClient service = new CalligraphyService.IcalligraphyClient();

            service.GetOnlineTemplateItemsCompleted += (o, e) =>
            {
                var data = e.Result;
                foreach (CalligraphyService.TemplateThumbnail iter in data)
                {
                    var temp = new TemplateItem();
                    temp.ID = iter.ID;
                    temp.Description = iter.Description;
                    temp.Image = iter.Thumbnail;
                    temp.Name = iter.Name;
                    Deployment.Current.Dispatcher.BeginInvoke(() => {

                        Uri uri = new Uri(temp.Image, UriKind.Absolute);
                        BitmapImage bm = new BitmapImage(uri);
                        bm.CreateOptions = BitmapCreateOptions.None;
                        bm.ImageOpened += (obj, ev) => {
                            temp.Bitmap = new WriteableBitmap((BitmapImage)obj);
                        };
                        this.OnlineTemplates.Add(temp);
                    });
                }
            };
            service.GetOnlineTemplateItemsAsync();


        }
        public void LoadTemplateItem()
        {
            SaveTemplateInfo templateManager = new SaveTemplateInfo();
            ObservableCollection<Template> templates = templateManager.GetData();

            foreach (var iter in templates)
            {
                Deployment.Current.Dispatcher.BeginInvoke(new AddTemplateToTemplateItemDelegate(AddTemplateToTemplateItem), iter);
            }
            //templateItems.Add(new TemplateItem() { Name = "calligraphy", Image = "Resources/Templates/calligraphy.jpg" });
            //templateItems.Add(new TemplateItem() { Name = "love", Image = "Resources/Templates/love.jpg" });
            //templateItems.Add(new TemplateItem() { Name = "wedding", Image = "Resources/Templates/wedding.jpg" });
            //templateItems.Add(new TemplateItem() { Name = "birthday", Image = "Resources/Templates/birthday.jpg" });
            //templateItems.Add(new TemplateItem() { Name = "noel", Image = "Resources/Templates/noel.jpg" });
            //templateItems.Add(new TemplateItem() { Name = "nature", Image = "Resources/Templates/nature.jpg" });
            //templateItems.Add(new TemplateItem() { Name = "happy new year", Image = "Resources/Templates/happynewyear.jpg" });
            //templateItems.Add(new TemplateItem() { Name = "happy teacher's day", Image = "Resources/Templates/teach.jpg" });

            //ObservableCollection<Template> templates = new ObservableCollection<Template>();

            //Template template;
            ////calligraphy
            //#region calligraphy
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background1.jpg";
            //template.TextControl.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithufap.ttf#VNI-HLThuphap",
            //        FontSize = 187.5,
            //        Foreground = "255_0_0_0",
            //        Height = 0,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 24,
            //        Type = 1,
            //        UnicodeText = "Nghixa",
            //        Text = "Nghóa",
            //        Top = 144,
            //        Width = 0
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/VNI-Ariston.TTF#VNI-Ariston",
            //        FontSize = 25,
            //        Foreground = "255_223_176_101",
            //        Height = 66,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = -15,
            //        Type = 0,
            //        UnicodeText = " Vietnamese calligraphy",
            //        Text = " Vietnamese calligraphy",
            //        Top = 744,
            //        Width = 353
            //    }
            //);
            //templates.Add(template);

            //#endregion
            ////love
            //#region love
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background8.jpg";
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 0,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithuphapslogan.ttf#VNI-Slogan",
            //        FontSize = 31.25,
            //        Foreground = "255_255_255_255",
            //        Height = 143,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 164,
            //        Type = 1,
            //        UnicodeText = " Lafm mej cura con anh em nhes!!!",
            //        Text = " Laøm meï cuûa con anh em nheù!!!",
            //        Top = 256,
            //        Width = 213
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/VNI-Commerce-Bold-Italic.TTF#VNI-Commerce",
            //        FontSize = 48.75,
            //        Foreground = "255_244_198_124",
            //        Height = 100,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 210,
            //        Type = 0,
            //        UnicodeText = " I Love You",
            //        Text = " I Love You",
            //        Top = 710,
            //        Width = 300
            //    }
            //);
            //templates.Add(template);
            //#endregion
            ////wedding
            //#region wedding
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background14.jpg";
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vniongdo.ttf#.TMC-Ong Do",
            //        FontSize = 48.75,
            //        Foreground = "255_0_0_255",
            //        Height = 0,
            //        Type = 1,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 357,
            //        UnicodeText = "Trawm \nNawm \nHajnh \nPhusc",
            //        Text = "Traêm \nNaêm \nHaïnh \nPhuùc",
            //        Top = -11,
            //        Width = 0
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/VNI-Allegie.TTF#VNI-Allegie",
            //        FontSize = 48.75,
            //        Foreground = "255_5_68_5",
            //        Height = 120,
            //        Type = 0,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = -7,
            //        UnicodeText = " Happy wedding",
            //        Text = " Happy wedding",
            //        Top = 690,
            //        Width = 358
            //    }
            //);
            //templates.Add(template);
            //#endregion
            ////birthday
            //#region brithday
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background12.jpg";
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithufap2.ttf#VNI-Thufap2",
            //        FontSize = 48.75,
            //        Foreground = "255_129_231_219",
            //        Height = 0,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 197,
            //        Type = 1,
            //        UnicodeText = "Happy",
            //        Text = "Happy",
            //        Top = -17,
            //        Width = 0
            //    }
            //);
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithufap2.ttf#VNI-Thufap2",
            //        FontSize = 48.75,
            //        Foreground = "255_131_229_219",
            //        Height = 0,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 243,
            //        Type = 1,
            //        UnicodeText = "Birthday",
            //        Text = "Birthday",
            //        Top = 72,
            //        Width = 0
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vniongdo.ttf#.TMC-Ong Do",
            //        FontSize = 62.5,
            //        Foreground = "255_139_0_0",
            //        Height = 0,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 269,
            //        Type = 1,
            //        UnicodeText = "Toos Trinh",
            //        Text = "Toá Trinh",
            //        Top = 663,
            //        Width = 0
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithufapfan.ttf#VNI-Thufapfan",
            //        FontSize = 48.75,
            //        Foreground = "255_139_0_0",
            //        Height = 117,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 299,
            //        Type = 1,
            //        UnicodeText = "02.11",
            //        Text = "02.11",
            //        Top = 618,
            //        Width = 162
            //    }
            //);
            //templates.Add(template);
            //#endregion
            ////noel
            //#region noel
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background10.jpg";
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/VNI-Ariston.TTF#VNI-Ariston",
            //        FontSize = 55,
            //        Foreground = "255_255_255_0",
            //        Height = 192,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = -15,
            //        UnicodeText = " Merry Christmas",
            //        Text = " Merry Christmas",
            //        Top = 618,
            //        Type = 0,
            //        Width = 346
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/VNI-Auchon-Bold.TTF#VNI-Auchon",
            //        FontSize = 43.75,
            //        Foreground = "255_255_255_0",
            //        Height = 116.0,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 20,
            //        UnicodeText = "Giasng Sinh An Lafnh",
            //        Text = "Giaùng Sinh An Laønh",
            //        Top = -4,
            //        Type = 1,
            //        Width = 469
            //    }
            //);
            //templates.Add(template);
            //#endregion
            ////nature
            //#region nature
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background13.jpg";
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnibriquet.ttf#VNI-Briquet",
            //        FontSize = 48.75,
            //        Foreground = "255_255_255_0",
            //        Height = 0,
            //        Width = 0,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = -5.0,
            //        Top = 704,
            //        Type = 1,
            //        Text = "Thieân nhieân höõu tình",
            //        UnicodeText = "Thieen nhieen huwxu tifnh"
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/VNI-Aztek.TTF#VNI-Aztek",
            //        FontSize = 37.5,
            //        Foreground = "255_165_42_42",
            //        Height = 88,
            //        Width = 358,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 152,
            //        Top = -15,
            //        Type = 0,
            //        Text = " Nature beauty",
            //        UnicodeText = " Nature beauty"
            //    }
            //);
            //templates.Add(template);
            //#endregion
            ////happynewyear
            //#region happy new year
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background11.jpg";
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithufap.ttf#VNI-HLThuphap",
            //        FontSize = 48.75,
            //        Foreground = "255_255_255_0",
            //        Height = 0,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = -1,
            //        Type = 0,
            //        Text = " Happy \n New \n Year",
            //        UnicodeText = " Happy \n New \n Year",
            //        Top = 98,
            //        Width = 0
            //    }
            //);
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithufap2.ttf#VNI-Thufap2",
            //        FontSize = 48.75,
            //        Foreground = "255_255_255_0",
            //        Height = 0,
            //        IsBold = false,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 314,
            //        Type = 1,
            //        UnicodeText = " Xuaan \n Quys \n Tyj \n 2013",
            //        Text = " Xuaân \n Quyù \n Tî \n 2013",
            //        Top = 1,
            //        Width = 0
            //    }
            //);
            //templates.Add(template);
            //#endregion
            ////teach
            //#region teach
            //template = new Template();
            //template.Background = "Resources/Backgrounds/background3.jpg";
            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/vnithufap.ttf#VNI-HLThuphap",
            //        FontSize = 48.75,
            //        Foreground = "255_0_0_0",
            //        Height = 0,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = 328,
            //        Type = 2,
            //        Text = "Toân \nSö \nTroïng \nÑaïo",
            //        UnicodeText = "Toon \nSuw \nTrojng \nDDajo",
            //        Top = -25,
            //        Width = 0
            //    }
            //);

            //template.TextControls.Add(
            //    new TextControlInfo()
            //    {
            //        Align = 2,
            //        FontFamily = "/ThuPhap;component/Resources/Fonts/VNI-Commerce-Bold-Italic.TTF#VNI-Commerce",
            //        FontSize = 35.0,
            //        Foreground = "255_0_0_0",
            //        Height = 74.0,
            //        IsBold = true,
            //        IsSelected = false,
            //        IsItalic = false,
            //        Left = -15,
            //        Type = 0,
            //        Text = " Learn, learn and once again, learn!",
            //        UnicodeText = " Learn, learn and once again, learn!",
            //        Top = 730,
            //        Width = 516
            //    }
            //);
            //templates.Add(template);
            //#endregion

            App.TemplateStored = templates;

            //foreach (var item in templateItems)
            //{
            //    Deployment.Current.Dispatcher.BeginInvoke(new AddItemToTemplateItemDelegate(AddItemToTemplateItem), item);
            //}
        }
        //public event FinishedReadGalleryDelegate FinishedReadGalleryEvent;
        public void UpdateGalleryItem()
        {
            //this.GalleryItems.Add(new GalleryItem() { Name = string.Format("TP_{0}", DateTime.Now.ToString("yyyyMMddhhmmss")), Image = "Resources/Backgrounds/backgroundt2.jpg", Date = DateTime.Now });
            //this.GalleryItems.Add(new GalleryItem() { Name = string.Format("TP_{0}", DateTime.Now.ToString("yyyyMMddhhmmss")), Image = "Resources/Backgrounds/backgroundt2.jpg", Date = DateTime.Now });
            //this.GalleryItems.Add(new GalleryItem() { Name = string.Format("TP_{0}", DateTime.Now.ToString("yyyyMMddhhmmss")), Image = "Resources/Backgrounds/backgroundt2.jpg", Date = DateTime.Now });
            //this.GalleryItems.Add(new GalleryItem() { Name = string.Format("TP_{0}", DateTime.Now.ToString("yyyyMMddhhmmss")), Image = "Resources/Backgrounds/backgroundt2.jpg", Date = DateTime.Now });
            //this.GalleryItems.Add(new GalleryItem() { Name = string.Format("TP_{0}", DateTime.Now.ToString("yyyyMMddhhmmss")), Image = "Resources/Backgrounds/backgroundt2.jpg", Date = DateTime.Now });
            SaveGalleryData gallery = new SaveGalleryData();
            var galleryItems = gallery.RetrieveData();
            //if (FinishedReadGalleryEvent != null)
            //{
            //    FinishedReadGalleryEvent(galleryItems.Gallery.Count);
            //}

            
            if (galleryItems != null)
            {
                foreach (var item in galleryItems.Gallery)
                {
                    GalleryItem newItem = new GalleryItem()
                    {
                        Name = item.Name,
                        Image = item.Image,
                        Date = item.Date
                    };

                    

                    Deployment.Current.Dispatcher.BeginInvoke(new AddItemToGalleryDelegate(AddItemToGallery), newItem);
                }
            }
        }

        private delegate void AddItemToGalleryDelegate(GalleryItem Item);
        private void AddItemToGallery(GalleryItem Item)
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(Item.Image, FileMode.Open, FileAccess.Read))
                {
                    WriteableBitmap writeableBitmap = new WriteableBitmap(0, 0).FromStream(fileStream);
                    var result = writeableBitmap.Crop(0, (writeableBitmap.PixelHeight - writeableBitmap.PixelWidth) / 2, writeableBitmap.PixelWidth, writeableBitmap.PixelWidth);
                    fileStream.Close();
                    Item.Bitmap = result;
                }
            }
            this.GalleryItems.Insert(0, Item);
        }
    }
}
